package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.*;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.mapper.PostMapper;
import com.itheima.wisdomnext.mapper.TopicMapper;
import com.itheima.wisdomnext.service.FavoriteService;
import com.itheima.wisdomnext.service.FollowService;
import com.itheima.wisdomnext.service.TopicService;
import com.itheima.wisdomnext.util.TopicS_Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TopicServiceImpI implements TopicService {

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserServiceImpI userService; // 注入用户服务层

    @Autowired
    private FavoriteService favoriteService; // 注入收藏服务层

    @Autowired
    private FollowService followService; // 注入关注服务层

    @Autowired
    private PostServiceImpl postService; // 注入帖子服务层

    @Override
    public Topic getTopicWithPosts(Integer tid, Long userId) {
        // 获取话题详情
        Topic topic = topicMapper.getTopicById(tid);
        if (topic == null) {
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"话题不存在");
        }

        // 查询与话题关联的帖子
        List<Post> posts = postMapper.getPostsByTopicId(tid);
        List<Postshow> postshows = new ArrayList<>();
        for (Post post : posts) {
            Postshow postshow = new Postshow();
            postshow.setId(post.getId());

            // 获取每个帖子的用户信息
            List<Users> userList = userService.getUserByIdPost(post.getUserid());
            postshow.setUsers(userList);

            // 设置帖子其他信息
            postshow.setTitle(post.getTitle());
            postshow.setContent(post.getContent());
            postshow.setCategoryId(post.getCategoryId());
            postshow.setViews(post.getViews());
            postshow.setLikes(post.getLikes());
            postshow.setCreatedAt(post.getCreatedAt());
            postshow.setBanned(post.getBanned());
            postshow.setApproved(post.getApproved());
            postshow.setVideoUrl(post.getVideoUrl());
            postshow.setCommentPostId(post.getCommentPostId());
            postshow.setLocation(post.getLocation());
            postshow.setQuestionPostId(post.getQuestionPostId());

            // 获取每个帖子的图片列表
            List<String> images = postMapper.getImagesByPostId(post.getId());
            postshow.setImages(images);

            // 查询问答帖子的相关信息并设置
            if (post.getQuestionPostId() != null) {
                QaPost qaPost = postService.getQaPostById(Long.valueOf(post.getQuestionPostId()));
                if ("choice".equals(qaPost.getQuestionType())) {
                    // 如果是选择题，处理选项
                    List<QaAnswerOption> options = postService.getOptionsByQuestionId(qaPost.getId());
                    qaPost.setAnswerOptions(options);  // 设置选项
                }
                postshow.setQaPost(qaPost);
            }

            // 如果有用户 ID，检查用户是否点赞、收藏、关注该帖子
            if (userId != null) {
                // 检查用户是否点赞该帖子
                boolean likedByUser = postService.isPostLikedByUser(post.getId(), Math.toIntExact(userId));
                postshow.setLikedByUser(likedByUser);

                // 检查用户是否收藏该帖子
                boolean favoritedByUser = favoriteService.isPostFavorited(Math.toIntExact(userId), post.getId()) > 0;
                postshow.setFavoritedByUser(favoritedByUser);

                // 查询用户是否关注该作者
                boolean followedByUser = followService.isUserFollowing(Math.toIntExact(userId), Math.toIntExact(post.getUserid()));
                postshow.setFollowedByUser(followedByUser);
            }

            // 将每个帖子的详细信息添加到 postshows 列表
            postshows.add(postshow);
        }

        // 将帖子信息添加到话题对象中
        topic.setPosts(postshows);
        return topic;
    }

    @Override
    public void createTopic(Topic topic) {
        int result = topicMapper.insertTopic(topic);
        if (result == 0){
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"创建话题失败");
        }
    }

    @Override
    public List<Topic> getAllTopics() {
        List<Topic> allTopics = topicMapper.getAllTopics();
        if (allTopics.isEmpty()){
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"查询话题为空");
        }
        return allTopics; // 调用 Mapper 层查询数据库
    }

    @Override
    public Topic getTopicById(Integer id) {
        Topic topicById = topicMapper.getTopicById(id);
        if (topicById == null){
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"获取话题失败");
        }
        return topicById;
    }

    @Override
    public void updateTopic(Topic topic) {
        int result = topicMapper.updateTopic(topic);
        // 如果话题更新成功，继续更新与话题关联的帖子的标题
        if (result <= 0) {
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"话题更新失败");
        }
        // 更新所有与话题关联的帖子
        postMapper.updatePostTitleByTopicId(topic.getId(), topic.getName());
    }

    @Override
    public void deleteTopic(Integer id) {
        int result = topicMapper.deleteTopic(id);
        if (result <= 0) {
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"话题删除失败");
        }
    }

    // 🔥 审核话题
    @Override
    public void approveTopic(Integer id) {
        int result = topicMapper.approveTopic(id);
        if (result <= 0) {
            TopicS_Util.isTrue(true, ErrorCode.FAILED,"话题审核失败");
        }
    }
}
